package com.bai.lease.model.untils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.bai.lease.model.entity.aliyun.AliOSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class OSSUtils {

    @Autowired
    private AliOSSProperties ossProperties;

    public String upload(MultipartFile file) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(
                ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret());

        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID() + suffix;

        ossClient.putObject(
                ossProperties.getBucketName(),
                fileName,
                file.getInputStream());

        ossClient.shutdown();

        return "https://" + ossProperties.getBucketName() + "."
                + ossProperties.getEndpoint() + "/" + fileName;
    }


}
